import React, { useState } from 'react'
import Container from 'components/Container'
import Add from './Add'
import './index.scss'
import { Store } from 'common/utils.ts'
import { Button } from 'antd'; 

const key = 'bookmark'
const statusArr = { 0: "未开始", 1: "进行中", 2: "已完成" }
const store = new Store(key)

export default function BookMark() {
    const [list, setList] = useState(store.get()||[])
    const underway = createLis(list.filter(t => t.status === 0), 'underway-li')
    const done = createLis(list.filter(t => t.status === 2), 'done-li')
    const beingprocessed = createLis(list.filter(t => t.status === 1), 'being-li')
    /**
     * 生成react li元素结构
     * @param {*} listArr 
     * @param {*} typeClass 
     */
    function createLis(listArr, typeClass) {
        return listArr.map(({ id, content, status }) => {
            return <li key={id} className={typeClass + ' item'}>
                <div className="text"> {content}</div>
                <div className="status"> {statusArr[status] || ''}</div>
                <div className="operation">
                    {
                        status < 2 && <Button type="primary" shape="small" onClick={() => {
                            const obj = list.find(l => l.id === id)
                            obj.status = status + 1
                            _setList([...list])
                        }}>{status === 1 ? '完成' : '开始处理'}</Button>
                    }
                    <Button type="primary" shape="small" danger onClick={() => {
                        // 删除确认
                        const index = list.findIndex(l => l.id === id)
                        const nweList = [...list]
                        nweList.splice(index, 1) 
                        _setList([...nweList])
                    }}>删除</Button>
                </div>
            </li>
        })
    }

    function _setList(arr) {
        setList(arr)
        store.set(arr)
    }

    return (
        <Container title="书签">
            <div className="bookmark-container">
                <Add onAdd={(obj) => _setList([...list, obj])} />
                <div className="book-row">
                    <h2>待处理 {underway.length}</h2>
                    <ul className="underway">
                        {underway}
                    </ul>
                </div>
                <div className="book-row">
                    <h2>处理中 {beingprocessed.length}</h2>
                    <ul className="beingprocessed">
                        {beingprocessed}
                    </ul>
                </div>
                <div className="book-row">
                    <h2>已处理 {done.length}</h2>
                    <ul className="done">
                        {done}
                    </ul>
                </div>
            </div>
        </Container>
    )
}